# -*- coding: utf-8 -*-

#
# fusion.http.util
#
# Copyright 2008 Helsinki Institute for Information Technology
# and the authors.
#
# Authors: Harri Hämäläinen <hhamalai@iki.fi>
#

# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

import cgi, re
from xml.etree.ElementTree import Element, tostring

def authorized_referer(environ):
    # The admin port could be locked down further using standard
    # techniques, but referrer checks are the best we can do in
    # isolating collections from each other for writing.  That is
    # because we serve all collections from the main port and thus
    # cannot keep per-collection secrets (since the browser's Same
    # Origin Policy doesn't come into effect in that case).

    referer = environ.get('HTTP_REFERER')
    if not referer:
        return False

    if referer.startswith('http://%s' % environ.get('HTTP_HOST')):
        return True

    return False

def get_fields(form, name):
    return form[name] if isinstance(form[name], list) else [form[name]]

def make_clickable_urls(text):
    text = escape_html(text)
    p = re.compile('(https?)://([:/?&=%.\-;]|\w)*')
    offset = 0
    tag_len =  len('<a href=""></a>')
    for it in re.finditer(p, text):
        start = it.start()+offset
        end = it.end()+offset
        url = text[start:end]
        offset = offset + len(url) + tag_len
        clickable = '<a href="%s">%s</a>' % (url, url)
        text = '%s%s%s' % ( text[:start],  clickable, text[end:] )
    return text

def format_xml(tag, text=None, **attributes):
    xml = Element(tag, **attributes)
    xml.text = text
    return tostring(xml)

def simplify_list(v):
    if type(v) == list:
        l = [x for x in v if x]
        if len(l) > 1:
            return l
        if len(l) == 1:
            return l[0]
        elif len(l) == 0:
            return ''
    else:
        return v
    

def escape_html(input):
    if type(input) in [str, unicode]:
        return cgi.escape(input, 1)
    else:
        return ''

if __name__ == '__main__':
    import doctest
    doctest.testmod()
